package com.wms.model;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import android.annotation.TargetApi;
import android.os.Build;
import android.os.StrictMode;

import com.wms.helper.Database;
import com.wms.helper.UserException;
import com.wms.assets.NewUser;
import com.wms.assets.User;

/**
 * Provides data methods necessary for the LoginPresenter to function.
 * @author Nathan
 */
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public class LoginModel {
	
	/**
	 * Simple constructor -- allows the Internet to be accessed on the main thread.
	 */
	public LoginModel()
	{
		StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
		StrictMode.setThreadPolicy(policy);
	}
	
	/**
	 *This method takes in username and passwords as parameters and checks against the database
	 *to authenticate the password. If the passwords match, it returns true, else, false.
	 *
	 *@param username
	 *@param password
	 *@return authentication - boolean whether authentication was successful
	 *
	 *@throws UserException - if username does not exist
	 */
	public User authentication(String username, String password) throws SQLException, UserException, InstantiationException, IllegalAccessException, ClassNotFoundException{
		
		Connection conn = Database.getReadConnection();		
		User user = null;
		
		PreparedStatement statement = conn.prepareStatement("SELECT password, role, status FROM User WHERE username=?");
		statement.setString(1, username);
		System.out.println(statement);
		
		ResultSet result = statement.executeQuery();
		
		if (!result.next()){
			throw new UserException("Username not found");
		}
		else{
			String dbpassword = result.getString("password");
	        if (password.compareTo(dbpassword)==0){
	        	user = new User(username, result.getString("status"), result.getString("role"));
			}
		}
		statement.close();
		conn.close();
		return user;
	}
	
	/**
	 * 
	 * @param username
	 * @throws SQLException
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 * @throws ClassNotFoundException
	 */
	public void suspendUser(String username) throws SQLException, InstantiationException, IllegalAccessException, ClassNotFoundException{
		Connection conn = Database.getWriteConnection();		
		
		PreparedStatement statement = conn.prepareStatement("UPDATE User SET status='suspended' WHERE username=?");
		statement.setString(1, username);
		
		statement.executeUpdate();
		
		statement.close();
		conn.close();
	}
	
	/**
	 *This method takes in a new user as a parameter for a new account and attempts
	 *to insert it into the database
	 *
	 *@param newUser - new user
	 *@return result - no. of rows affected. 0 for unsuccessful, 1 for success.
	 *
	 *@throws UserException - if username already exists
	 */
	public int createUser(NewUser newUser) throws SQLException, UserException, InstantiationException, IllegalAccessException, ClassNotFoundException{
		
		//boolean created = false;
		Connection conn = Database.getWriteConnection();
		PreparedStatement statement = conn.prepareStatement("INSERT INTO User (username,password,emailhidden,displayemail, role, status) VALUES (?,?,True,?, 'user', 'active')");
		statement.setString(1, newUser.getUsername());
		statement.setString(2, newUser.getPassword());
		statement.setString(3, newUser.getUsername());
		
		int result;
		try {
			
			result = statement.executeUpdate();
		} catch (SQLException e) {
			//created = false;
			throw new UserException("Username already taken");
		}
		
		statement.close();
		conn.close();
		
		
		return result;
				
	}
	
	
	/**
	 * 
	 * @return
	 * @throws SQLException
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 * @throws ClassNotFoundException
	 */
	public List<User> getUserList() throws SQLException, InstantiationException, IllegalAccessException, ClassNotFoundException{
		
		List<User> users = null;
		Connection conn = Database.getReadConnection();	
		
		PreparedStatement statement = conn.prepareStatement("SELECT * FROM User");
		//System.out.println(statement);
		
		ResultSet result = statement.executeQuery();
		
		if (result.next()){
			users = new ArrayList<User>();
			String username;
			String status;
			String role;
			do 
			{
	            username = result.getString("username");
	            status = result.getString("status");
	            role = result.getString("role");
	            
	            users.add(new User(username, status, role));
	        } while(result.next());
		}
		statement.close();
		conn.close();
		return users;
	}
	
	/**
	 * 
	 * @return
	 * @throws SQLException
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 * @throws ClassNotFoundException
	 */
	public List<User> getSuspendedUserList() throws SQLException, InstantiationException, IllegalAccessException, ClassNotFoundException{
		List<User> users = getUserList();
		if (users != null){
			List<User> suspended = new ArrayList<User>();
			for (User user: users){
				if (user.getStatus().equals("suspended") || user.getStatus().equals("suspend")){
					suspended.add(user);
				}
			}
			return suspended;
		}
		else return null;
		
	}
}
